<?php
namespace control;
/*
*财务会计-工资统计类
*/

class salaryStatisticsClass extends adIndexClass
{
    private const page = 'salaryStatistics';
    private const table = 'work_sign_record';
    private const title = '工资统计';

    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html =<<<eof
<style>
.home-warp{flex-direction: column}
.flex-div > .data-widget:nth-child(2n-1){margin-right: 0}
#salary-table{padding: 0 10px 10px 10px}
  </style>
eof;
        $html.=$this->html();
        //返回
        return $this->homeFun($html);
    }

    /**
     * 默认主页
     */
    private function html(): string
    {
        // 搜索文本框
        $searchTxt = self::searchText([
            'click' => "search_line('salaryTrendForm','salaryStatistics','salaryTrend')",
            'search' => true,
            "name" => "month",
            "title" => "时间段",
            "class" => "line28",
            "value" => date('Y-m', strtotime("-12 month")) . ' ~ ' . date('Y-m'),
            'laydate' => ['type' => 'month', 'range' => '~']
        ]).self::searchText(array('name' => 'stid', 'id'=>'salaryTrend', 'click' => "search_line('salaryTrendForm','salaryStatistics','salaryTrend')", 'title' => '员工', 'search' => true)) . hidden(array('name' => 'stid', 'value' => ''));

        //工资趋势
        $salaryTrendHtml = $this->dataBoard(['title' => '工资趋势','searchText'=>$searchTxt, 'fun' => 'salaryTrend']);

        // 搜索文本框
        $searchTxt = self::searchText(array('name' => 'stid', 'id'=>'salaryType', 'click' => "search_line('salaryTypeForm','salaryStatistics','salaryType')", 'title' => '员工', 'search' => true)) . hidden(array('name' => 'stid', 'value' => ''));

        //支出类别
        $salaryTypeHtml = $this->dataBoard(['title' => '支出类别','searchText'=>$searchTxt,  'fun' => 'salaryType']);
        // 搜索文本框
        $searchTxt = self::searchText([
                'click' => "search_line('salaryDistributedForm','salaryStatistics','salaryDistributed')",
                'search' => true,
                "name" => "month",
                "title" => "时间段",
                "class" => "line28",
                "value" => date('Y-m', strtotime("-6 month")) . ' ~ ' . date('Y-m'),
                'laydate' => ['type' => 'month', 'range' => '~']
            ]);

        //工资分布
        $salaryDistributedHtml = $this->dataBoard(['title' => '工资分布', 'searchText'=>$searchTxt, 'fun' => 'salaryDistributed']);


        return <<<EOT
        <div class="home-warp">
            <div>
             <div class="flex-div">
                <div class="flex-div-children data-widget">
                    {$salaryTrendHtml}
                </div>
                <div class="flex-div-children colum-line"></div>
                <div class="flex-div-children data-widget" >
                    {$salaryTypeHtml}
                </div>
                <div class="flex-div-children colum-line"></div>
                <div class="flex-div-children data-widget" >
                    {$salaryDistributedHtml}
                </div>
                </div>
            </div>
            <div class="flex-div">
            <div class="flex-div-children data-widget" style="width: 97.7%">
                <div class="frame-title"><span class="title-card">数据表</span>&emsp;<span style="font-family:'Arial Normal', 'Arial';font-weight:400;text-decoration:none;color:#AAAAAA;">单位：万元</span></div>
                <div id="salary-table" class="data-box-show">
                
                </div>
            </div>
            </div>
        </div>
    </div>
    <script src='{$this->root}static/javascript/echarts.min.js'></script>
    <script>
    
$(function() {

    search_line('salaryTrendForm','salaryStatistics','salaryTrend');
    search_line('salaryTypeForm','salaryStatistics','salaryType');
    search_line('salaryDistributedForm','salaryStatistics','salaryDistributed')
    requestTable();
    $("[name='stid']").each(function (){
          $(this).bigAutocomplete({
            url:root + 'control/adIndex.html?cla=component&fun=getStaff',
            callback:function(data,e){
                e.parent().siblings("input[name='stid']").val(data.id)
        }})  
    })
    $("#salary-table").on('click')
})
function search_line(formName,cla,fun) {
     $("#" + fun + "Html").html("数据查询中，请稍后。。。");
    $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun, $("[name='" + formName + "']").serialize(), function (data) {
         $("#" + fun + "Html").html(data.html);
    }, "json");
}
function requestTable(year=''){
    $.post(root + "control/adIndex.html?cla=salaryStatistics&fun=salaryTable", {year:year}, function (data) {
         $("#salary-table").html(data.html);
    }, "json");
}
    </script>
EOT;
    }

    public function sumMoney($type,$month)
    {
        return match ($type){
            '工资总额'=>find(array('table'=>'work_sign_record','where'=>"month = '$month' and isPay = 1",'sum'=>"payMoney")),
            '基本工资'=>find(array('table'=>'work_sign_record','where'=>"month = '$month' and isPay = 1",'sum'=>"baseMoney")),
            '岗位工资'=>find(array('table'=>'work_sign_record','where'=>"month = '$month' and isPay = 1",'sum'=>"jobMoney")),
            '绩效工资'=>find(array('table'=>'work_sign_record','where'=>"month = '$month' and isPay = 1",'sum'=>"performance")),
            '社保'=>find(array('table'=>'work_sign_record','where'=>"month = '$month' and isPay = 1",'sum'=>"insure")),
            '公积金'=>find(array('table'=>'work_sign_record','where'=>"month = '$month' and isPay = 1",'sum'=>"providentFund")),
            '个税'=>find(array('table'=>'work_sign_record','where'=>"month = '$month' and isPay = 1",'sum'=>"personalTax")),
            '其他'=>find(array('table'=>'work_sign_record','single'=>"month = '$month' and isPay = 1",'field'=>"ifnull(sum(payMoney-baseMoney-performance-jobMoney-insure-providentFund-personalTax),0) as money"))['money'],
            default=>0,
        };
    }

    /**
     * 工资表
     * @return bool|string
     */
    public function salaryTable(): bool|string
    {
        $year = $this->post('year')?:date('Y');
        //工资表
        $temp[]= text(array('name'=>'year','class'=>'textPrice','laydate'=>['type'=>'year','done'=>"function(e){requestTable(e)}"],'value'=>$year));
        for ($i=1;$i<=12;$i++){
            $temp[] = $i.'月';
        }
        $classifyOption = ['工资总额','基本工资','岗位工资','绩效工资','社保','公积金','个税','其他'];
        $tr[] = $temp;
        foreach ($classifyOption as $val){
            $temp=[];
            switch ($val){
                case '基本工资':
                    $temp[] = '其中：'.$val;
                    break;
                case '工资总额':
                case '岗位工资':
                case '绩效工资':
                case '社保':
                case '公积金':
                case '个税':
                case '其他':
                $temp[] = $val;
                break;
            }
            for ($i=1;$i<=12;$i++){
                $month = $year.'-'.sprintf("%02d",$i);
                $money = $this->sumMoney($val,$month);
                $temp[] = floatval((float)$money/10000);
            }
            $tr[] = $temp;
        }
        $json['html'] = $this->tableMany(array('tr'=>$tr,'displayFields'=>false));
        return json_encode($json,320);
    }

    /**
     * 工资分布
     */
    public function salaryDistributed(){
        $where = '';
        $month = $this->post('month');
        if ($month){
            $arr = explode('~', $month);
            $arr[0] = trim($arr[0]);
            $arr[1]   = trim(end($arr));
            $where=" and month >= '$arr[0]' and month <='$arr[1]'";
        }
        $yData   = [];
        $xData = [];
        $typeOption = [
            '5k以下'=>['min'=>0,'max'=>5000],
            '5-10k'=>['min'=>5000,'max'=>10000],
            '10-15k'=>['min'=>10000,'max'=>15000],
            '15-20k'=>['min'=>15000,'max'=>20000],
            '20-25k'=>['min'=>20000,'max'=>25000],
            '25-30k'=>['min'=>25000,'max'=>30000],
            '30k以上'=>['min'=>30000,'max'=>0],
        ];
        foreach ($typeOption as $type=>$val) {
            $xData[] = $type;
            $and = $where." and payMoney>='$val[min]'";
            if ($val['max'] >0){
                $and.=" and payMoney < '$val[max]'";
            }
            $num = static::total(array('table'=>'work_sign_record','where'=>"1=1 {$and} and isPay = 1"));
            $yData[] = ['name'=>$type,'value'=>$num];
        }
        $yData = json_encode($yData,320);
        $xData = json_encode($xData,320);
        $option = "
		var option = { tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  toolbox: {
    
  },
  legend: {
    data: ['人数']
  },
  xAxis: [
    {
      type: 'category',
      data: {$xData},
      axisPointer: {
        type: 'shadow'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '人数',
       interval: 1,
      axisLabel: {
        formatter: '{value} 人'
      }
    }
  ],
  series: [
    {
      name: '人数',
      type: 'bar',
      tooltip: {
        valueFormatter: function (value) {
          return value + ' 人';
        }
      },
      data: {$yData}
    }
  ]
		};";
        $json['html'] = $this->echarts($option);
        return json_encode($json, 320);
    }

    public function salaryType(){
        $where = '';
        $stid = $this->post('stid');
        if ($stid){
            $where=" and stid = '".$stid."'";
        }
        $yData   = [];
        $typeOption = [
            '基本工资',
            '岗位工资',
            '社保',
            '公积金',
            '个税',
            '其他',
        ];
        foreach ($typeOption as $type) {
            $payMoney  = match ($type){
                '基本工资'=>find(array('table'=>'work_sign_record','where'=>"1=1 {$where} and isPay = 1",'sum'=>"baseMoney")),
                '岗位工资'=>find(array('table'=>'work_sign_record','where'=>"1=1 {$where} and isPay = 1",'sum'=>"jobMoney")),
                '社保'=>find(array('table'=>'work_sign_record','where'=>"1=1 {$where} and isPay = 1",'sum'=>"insure")),
                '公积金'=>find(array('table'=>'work_sign_record','where'=>"1=1 {$where} and isPay = 1",'sum'=>"providentFund")),
                '个税'=>find(array('table'=>'work_sign_record','where'=>"1=1 {$where} and isPay = 1",'sum'=>"personalTax")),
                '其他'=>find(array('table'=>'work_sign_record','single'=>"1=1 {$where} and isPay = 1",'field'=>"ifnull(sum(payMoney-baseMoney-jobMoney-insure-providentFund-personalTax),0) as money"))['money'],
            };
            $yData[] = ['name'=>$type,'value'=>$payMoney];
        }
        $yData = json_encode($yData,320);
        $option = "
		var option= {
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '5%',
    left: 'center'
  },
  series: [
    {
      name: '支出类别',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '20',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: {$yData}
    }
  ]
};";
        $json['html'] = $this->echarts($option);
        return json_encode($json, 320);
    }
    /**
     * 工资趋势
     */
    public function salaryTrend(): bool|string
    {
        $where = '';
        $stid = $this->post('stid');
        if ($stid){
            $where=" and stid = '".$stid."'";
        }
        $month = $this->post('months');
        if (!empty($month)) {
            $timeArr = explode(' ~ ', $month);
        } else {
            $timeArr[0] = $this->date;
            $timeArr[1] = date('Y-m-d', strtotime("-12 month"));
        }
        $dataArr = self::dateRange($timeArr[0], $timeArr[1]);
        $xData   = [];
        $yData   = [];
        $perData = [];
        foreach ($dataArr as $month) {
            $xData[]  = date('m月',strtotime($month.'-01'));
            $payMoney  = find(array('table'=>'work_sign_record','where'=>"month = '$month' {$where} and isPay = 1",'sum'=>"payMoney"));
            $people = static::total(array('table'=>'work_sign_record','where'=>"month = '$month' {$where} and isPay = 1"));
            $yData[] = $payMoney/10000;
            $perData[] = $people>0?($payMoney/$people)/10000:0;
        }
        $xData = json_encode($xData,320);
        $yData = json_encode($yData,320);
        $perData = json_encode($perData,320);
        $option = "
		var option = { tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  toolbox: {
    
  },
  legend: {
    data: ['工资', '人均工资']
  },
  xAxis: [
    {
      type: 'category',
      data: {$xData},
      axisPointer: {
        type: 'shadow'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '工资',
      axisLabel: {
        formatter: '{value} 万元'
      }
    },
    {
      type: 'value',
      name: '人均工资',
      axisLabel: {
        formatter: '{value} 万元'
      }
    }
  ],
  series: [
    {
      name: '工资',
      type: 'bar',
      tooltip: {
        valueFormatter: function (value) {
          return value + ' 万元';
        }
      },
      data: {$yData}
    },
    {
      name: '人均工资',
      type: 'line',
      yAxisIndex: 1,
      tooltip: {
        valueFormatter: function (value) {
          return value + ' 万元';
        }
      },
      data: {$perData}
    }
  ]
		};";
        $json['html'] = $this->echarts($option);
        return json_encode($json, 320);
    }


    /**
     * 数据看板
     *
     * @param array $data 格式 [ 'title'=>'标题', 'fun'=>'数据源函数', 'condition'=> '显示查询条件，为空表示显示' ]
     */
    public  function dataBoard(array $data): string
    {
        $html        = '';
        $isCondition = (!isset($data['condition']) || $data['condition'] !== false);
        if ($isCondition) {
            $data['searchText'] = $data['searchText']??'';
            $dateText =$data['searchText'];
            $html     .= <<<EOT
			<form name='{$data['fun']}Form' onsubmit="return searchFormSub('salaryStatistics', '{$data['fun']}')">
			    <div class="frame-title">
				<span class="title-card">{$data['title']}</span>
				$dateText
				</div>
			</form>
EOT;
        }
        $isCondition = settype($isCondition, "int");
        $html        .= <<<EOT
<div id='{$data['fun']}Html' class='data-box-show'>数据查询中。。。</div>
EOT;
        //返回
        return $html;
    }
}
